package zm.irc.message.processor;

import java.util.LinkedList;
import java.util.List;

import zm.irc.client.IrcClient;
import zm.irc.ioc.ApplicationContext;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;
import zm.irc.ioc.beanActoin.AfterContexinItialize;
import zm.irc.message.receive.IrcReceiveMessage;

@Service(isSinglet = true)
public class MessageProcessorCenter implements AfterContexinItialize{

    @AutoWired
    private IrcClient client;

    @AutoWired
    private ApplicationContext context;
    private LinkedList<IrcMessageProcessor> impList;

    private volatile boolean isInited = false;
    
    @Override
    public void doAction() {
        this.init();
        
    }

    private void init(){
        if(isInited){
            return;
        }
        synchronized(this){
            if(isInited){
                return;
            }
           
            this.isInited = true;
            List<IrcMessageProcessor> processors = context.getByType(IrcMessageProcessor.class);

            for(IrcMessageProcessor p : processors){
                this.add(p);
            }
        }
    }

    private void add(IrcMessageProcessor ip){
        this.impList.add(ip);
    }

    public MessageProcessorCenter(){
        this.impList = new LinkedList<>();
    }


    public void process(IrcReceiveMessage msg){
        if(msg == null){
            return;
        }
        for( IrcMessageProcessor imp : this.impList){
            boolean shouldContinue = imp.processor(this.client,msg);
            if( !shouldContinue){
                break;
            }
        }
    }
}
